package com.edgclub.edg.activity;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.edgclub.edg.Constant;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.PermissionsEmum;
import com.edgclub.edg.R;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.UserApi;
import com.edgclub.edg.api.param.UserParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.huanxin.DemoHelper;
import com.edgclub.edg.huanxin.db.DemoDBManager;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.UserData;
import com.edgclub.edg.utils.util.CommonUtils;
import com.edgclub.edg.utils.util.CryptUtil;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.rockerhieu.emojicon.emoji.SerializeManager;
import com.squareup.otto.ThreadEnforcer;
import com.umeng.analytics.MobclickAgent;
import com.zhzhinn.activity.ZZRegisterSelectIconActivity;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 登陆
 */
public class GzLoginActivity extends GzBaseActivity implements OnClickListener, VolleyListener {


    private EditText username;
    private EditText password;
    private RelativeLayout tvFindPsw;
    private ImageView one, two;

    private UserPrefUtils userPrefUtil;
    private UserApi userApi;
    private int type = 0;
    private User user;
    private String getpsw = "1";
    private String zhuce = "3";
    private String remember_phone;
    private boolean isfirst;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        remember_phone = getIntent().getStringExtra("remember_phone");
        userApi = new UserApi(this);
        userPrefUtil = new UserPrefUtils(this);
        if(getIntent().getBooleanExtra("remove",false)){
                    Toast.makeText(this,
                            StringUtils.getString(R.string.banaccount2), Toast.LENGTH_LONG).show();
        }
        setContenview();
    }

    private void setContenview() {
        setContentView(R.layout.activity_gz_login);
        initView();
        ShareSDK.initSDK(this);
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).register(this);
    }

    private void initView() {

        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        one = (ImageView) findViewById(R.id.one);
        two = (ImageView) findViewById(R.id.two);
        if (!"".equals(remember_phone)&&null!=remember_phone){
            username.setText(remember_phone.toString());
        }

        findViewById(R.id.ll_weibo).setOnClickListener(this);
        findViewById(R.id.ll_weixin).setOnClickListener(this);
        findViewById(R.id.ll_qq).setOnClickListener(this);
        findViewById(R.id.btn_login).setOnClickListener(this);
        findViewById(R.id.btn_register).setOnClickListener(this);
        tvFindPsw = (RelativeLayout) findViewById(R.id.tv_findpsw);
        tvFindPsw.setOnClickListener(this);


        username.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (isfirst) {
                    one.setBackgroundResource(R.drawable.animback);
                    if (hasFocus) {
                        // 此处为得到焦点时的处理内容
                        AnimationDrawable animation = (AnimationDrawable) one.getBackground();
                        animation.start();
                        two.setVisibility(View.GONE);
                        one.setVisibility(View.VISIBLE);
                    } else {
                        // 此处为失去焦点时的处理内容
                        one.setVisibility(View.GONE);
                        two.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        password.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (isfirst) {
                    two.setBackgroundResource(R.drawable.anim);
                    if (hasFocus) {
                        // 此处为得到焦点时的处理内容
                        AnimationDrawable animation = (AnimationDrawable) two.getBackground();
                        animation.start();
                        two.setVisibility(View.VISIBLE);
                        one.setVisibility(View.GONE);
                    } else {
                        // 此处为失去焦点时的处理内容
                        one.setVisibility(View.VISIBLE);
                        two.setVisibility(View.GONE);
                    }
                }
            }
        });
        password.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                isfirst = true;
                return false;
            }
        });
        username.setSelection(username.length());
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn_register:
                Intent intent = new Intent(this, RegisterActivity.class);
                intent.putExtra("zhuce",zhuce);
                startActivity(intent);
                break;
            case R.id.btn_login:
                if ("".equals(username.getText().toString().trim())) {
                    Toast.makeText(this, "请输入帐号", Toast.LENGTH_SHORT).show();
                    return;
                }
//                if (username.getText().toString().length() < 11) {
//                    Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                if ("".equals(password.getText().toString().trim())) {
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                type = 0;
                loginm(type);
                break;
            case R.id.tv_findpsw:
                Intent intent1 = new Intent(this, RegisterActivity.class);
                intent1.putExtra("getpsw", getpsw);
                startActivity(intent1);
                break;
            case R.id.ll_weixin:
                if (CommonUtils.checkPackage(GzLoginActivity.this,
                        "com.tencent.mm")) {
                    Platform googlePlus3 = ShareSDK.getPlatform(Wechat.NAME);
                    googlePlus3.SSOSetting(false);  //设置false表示使用SSO授权方式
                    googlePlus3.setPlatformActionListener(mPlatformActionListener); // 设置分享事件回调
                    googlePlus3.showUser(null);
                } else {
                    showToast("尚未安装微信，请安装微信客户端");
                }

                break;
            case R.id.ll_weibo:
                Platform googlePlus2 = ShareSDK.getPlatform(SinaWeibo.NAME);
                googlePlus2.SSOSetting(false);  //设置false表示使用SSO授权方式
                googlePlus2.setPlatformActionListener(mPlatformActionListener); // 设置分享事件回调
                googlePlus2.showUser(null);
                break;
            case R.id.ll_qq:
                if (CommonUtils.checkPackage(GzLoginActivity.this,
                        "com.tencent.mobileqq")
                        || CommonUtils.checkPackage(GzLoginActivity.this, "com.tencent.qqlite")) {
                    Platform googlePlus1 = ShareSDK.getPlatform(QQ.NAME);
                    googlePlus1.SSOSetting(false);  //设置false表示使用SSO授权方式
                    googlePlus1.setPlatformActionListener(mPlatformActionListener); // 设置分享事件回调
                    googlePlus1.showUser(null);
                } else {
                    showToast("尚未安装QQ，请安装QQ客户端");
                }

                break;
        }

    }

    PlatformActionListener mPlatformActionListener = new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
            Message msg = new Message();
            msg.what = 0;
            msg.obj = platform;
            handlertmp.sendMessage(msg);
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            Message msg = new Message();
            msg.what = 2;
            msg.obj = platform;
            handlertmp.sendMessage(msg);
            platform.removeAccount();
        }

        @Override
        public void onCancel(Platform platform, int i) {
            Message msg = new Message();
            msg.what = 1;
            msg.obj = platform;
            handlertmp.sendMessage(msg);
            platform.removeAccount();

        }
    };

    Handler handlertmp = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                Platform plat = (Platform) msg.obj;
                String openId = plat.getDb().getUserId(); // 获取用户在此平台的ID
                String icon = plat.getDb().getUserIcon();
                String nickname = plat.getDb().getUserName();
                String sex = "1";
                if (!"m".equals(plat.getDb().getUserGender()))
                    sex = "0";
                if (QQ.NAME.equals(plat.getName())) {
                    checkBind(openId, icon, sex, nickname, "0");
                } else if (SinaWeibo.NAME.equals(plat.getName())) {
                    checkBind(openId, icon, sex, nickname, "2");
                    plat.removeAccount(true);
                } else if (Wechat.NAME.equals(plat.getName())) {
                    checkBind(openId, icon, sex, nickname, "1");
                }
            } else if (msg.what == 1) {
                showToast("授权取消");
            } else if (msg.what == 2) {
                showToast("授权错误");
            }
        }
    };

    private void checkBind(String openId, String icon, String sex, String nickname, String types) {
        UserParam params = new UserParam();
        params.setOpenId(openId);
        params.setTypes(types);
        params.setNick(nickname + "");
        params.setLogo(icon + "");
        params.setSex(sex);
        params.setChannel(GuZhiApplication.getInstance().getChannel());
        userApi.checkBind(params, this);
    }


    public void login() {
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
            return;
        }
        if (null == user)
            return;
        // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        DemoDBManager.getInstance().closeDB();
        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(user.getNick());
        // 调用sdk登陆方法登陆聊天服务器
        EMClient.getInstance().login(user.getImid(), userPrefUtil.getPSW(), new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().updateCurrentUserNick(user.getNick());
                DemoHelper.getInstance().init(GzLoginActivity.this);
                dismissDialog();
                if ("".equals(user.getLogo())) {
                    Intent intent = new Intent(GzLoginActivity.this,
                            ZZRegisterSelectIconActivity.class);
                    startActivity(intent);
                } else {
                    GuZhiApplication.isFirstMianActivity = true;
                    Intent intent = new Intent(GzLoginActivity.this,
                            GzMainActivity.class);
                    startActivity(intent);
                }
                finish();
                // 进入主页面
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(final int code, final String message) {

                runOnUiThread(new Runnable() {
                    public void run() {
                        dismissDialog();
                        switch (code) {
                            // 网络异常 2
                            case EMError.NETWORK_ERROR:
                                Toast.makeText(GzLoginActivity.this, "网络错误 " + message, Toast.LENGTH_LONG).show();
                                break;
                            // 无效的用户名 101
                            case EMError.INVALID_USER_NAME:
                                Toast.makeText(GzLoginActivity.this, "无效的用户名 "  + message, Toast.LENGTH_LONG).show();
                                break;
                            // 无效的密码 102
                            case EMError.INVALID_PASSWORD:
                                Toast.makeText(GzLoginActivity.this, "无效的密码 "  + message, Toast.LENGTH_LONG).show();
                                break;
                            // 用户认证失败，用户名或密码错误 202
                            case EMError.USER_AUTHENTICATION_FAILED:
                                Toast.makeText(GzLoginActivity.this, "用户认证失败，用户名或密码错误 "  + message, Toast.LENGTH_LONG).show();
                                break;
                            // 用户不存在 204
                            case EMError.USER_NOT_FOUND:
                                registerHx();
//                                Toast.makeText(GzLoginActivity.this, "用户不存在 "  + message, Toast.LENGTH_LONG).show();
                                break;
                            // 无法访问到服务器 300
                            case EMError.SERVER_NOT_REACHABLE:
                                Toast.makeText(GzLoginActivity.this, "无法访问到服务器 "  + message, Toast.LENGTH_LONG).show();
                                break;
                            // 等待服务器响应超时 301
                            case EMError.SERVER_TIMEOUT:
                                Toast.makeText(GzLoginActivity.this, "等待服务器响应超时 "  + message, Toast.LENGTH_LONG).show();
                                break;
                            // 服务器繁忙 302
                            case EMError.SERVER_BUSY:
                                Toast.makeText(GzLoginActivity.this, "服务器繁忙 "  + message, Toast.LENGTH_LONG).show();
                                break;
                            // 未知 Server 异常 303 一般断网会出现这个错误
                            case EMError.SERVER_UNKNOWN_ERROR:
                                Toast.makeText(GzLoginActivity.this, "未知的服务器异常 "  + message, Toast.LENGTH_LONG).show();
                                break;
                            default:
                                Toast.makeText(GzLoginActivity.this, "ml_sign_in_failed "  + message, Toast.LENGTH_LONG).show();
                                break;
                        }
//                        Toast.makeText(getApplicationContext(), code + getString(R.string.Login_failed) + message,
//                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void loginm(int type) {
        UserParam params = new UserParam();
        if (type == 1) {
            params.setPwd(userPrefUtil.getPSW());
            params.setUsername(userPrefUtil.getName());
        } else {
            params.setUsername(username.getText().toString().trim());
            params.setPwd(CryptUtil.md5(password.getText().toString().trim()));
        }
        // 开始登陆操作
        userApi.login(params, GzLoginActivity.this);
    }

    private void registerHx() {
        UserParam params = new UserParam();
        params.setUserId(user.getId());
        // 开始登陆操作
        userApi.login(params, GzLoginActivity.this);
    }

    @Override
    public void onStart(String tag) {
        showDialog(StringUtils.getString(R.string.logining), false);
    }

    @Override
    public void onSuccess(String response, String tag) {
        int code = JSONHelper.getResultCode(response);
        dismissDialog();
        if (ApiConfig.APIURL.URL_LOGIN.equals(tag)) {
            if (JSONHelper.isSuccess(response)) {
                UserData userData = JsonUtil.getMode(response, UserData.class);
                if (null != userData) {
                    user = userData.getData();
                    if (null != user) {
                        GuZhiApplication.getInstance().setMipush();
                        // 保存密码到用户信息
                        userPrefUtil.setIsLogin(true);
                        userPrefUtil.saveUser(user);
                        if(!GuZhiApplication.getInstance().isUpload)
                            GuZhiApplication.getInstance().getSysAdmin();
                        SerializeManager.saveFile(user.getId(), Constant.currentId);
                        if (type == 0) {
                            String role = Integer.toBinaryString(user.getRoleCode());
                            userPrefUtil.setDeletReply((user.getRoleCode() & PermissionsEmum.deletReply) > 0);
                            userPrefUtil.setDeletTopic((user.getRoleCode() & PermissionsEmum.deletTopic) > 0);
                            userPrefUtil.setRaiseTopic((user.getRoleCode() & PermissionsEmum.raiseTopic) > 0);
                            userPrefUtil.setMoveTopic((user.getRoleCode() & PermissionsEmum.moveTopic) > 0);
                            userPrefUtil.setReportTopic((user.getRoleCode() & PermissionsEmum.reportTopic) > 0);
                            userPrefUtil.setBanDevice((user.getRoleCode() & PermissionsEmum.banDevice) > 0);
                            userPrefUtil.setGroupAdmin((user.getRoleCode() & PermissionsEmum.groupAdmin) > 0);
                            userPrefUtil.saveName(username.getText().toString().trim());
                            user.setPsw(CryptUtil.md5(password.getText().toString().trim()));
                            userPrefUtil.savePSW(CryptUtil.md5(password.getText().toString().trim()));
                            login();
                            Log.d("TAG", role+"----onSuccess:raiseTopic---- "+(user.getRoleCode() & PermissionsEmum.raiseTopic));
                        } else {
                            Intent intent = null;
                            if ("".equals(user.getLogo())) {
                                intent = new Intent(GzLoginActivity.this,
                                        ZZRegisterSelectIconActivity.class);
                            } else {
                                GuZhiApplication.isFirstMianActivity = true;
                                intent = new Intent(GzLoginActivity.this,
                                        GzMainActivity.class);
                            }
                            startActivity(intent);
                            finish();

                        }

                    }
                }
            } else {
                dismissDialog();
                if (DemoHelper.getInstance().isLoggedIn()) {
                    logout();
                }
                if (code == 2004) {

                    Toast.makeText(GzLoginActivity.this,
                            StringUtils.getString(R.string.banaccount2), Toast.LENGTH_LONG)
                            .show();

                }

                if (code == 2001) {
                    Toast.makeText(GzLoginActivity.this, StringUtils.getString(R.string.loginerror),
                            Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(GzLoginActivity.this,
                            StringUtils.getString(R.string.interestcontent), Toast.LENGTH_LONG)
                            .show();
                }

            }
        } else if (ApiConfig.APIURL.URl_CHECK_BIND.equals(tag)) {
            if (JSONHelper.isSuccess(response)) {
                dismissDialog();
                UserData userData = JsonUtil.getMode(response, UserData.class);
                if (null != userData) {
                    user = userData.getData();
                    userPrefUtil .setIsLogin(true);
                    userPrefUtil.saveUser(user);
                    userPrefUtil.saveName(user.getPhone()+"");
                    userPrefUtil.savePSW(user.getPsw());
                    login();
                    MobclickAgent.onEvent(this,"EC_THIRD_REGISTER_SUCCESS");
                }
            } else {
                dismissDialog();
                showToast(JSONHelper.getResultMsg(response));
            }
        } else if (tag.equals(ApiConfig.APIURL.URL_REGISTERHX)) {
            if (JSONHelper.isSuccess(response)) {

            }
        }
    }

    @Override
    public void onFaile(VolleyError volleyError, String tag) {
        if (DemoHelper.getInstance().isLoggedIn()) {
            logout();
        }
        dismissDialog();
        ResultCode.toastVolleyError(GzLoginActivity.this, volleyError);
    }

    void logout() {
        DemoHelper.getInstance().logout(false, new EMCallBack() {

            @Override
            public void onSuccess() {
                dismissDialog();
                GzLoginActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        new UserPrefUtils(GzLoginActivity.this).clearUser();
                        startActivity(new Intent(GzLoginActivity.this, GzLoginActivity.class));
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(int code, String message) {
                dismissDialog();
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).unregister(this);
    }
}
